package com.djsearch.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.djsearch.R;
import com.djsearch.adapter.WanNengChildListAdapter;
import com.djsearch.adapter.WanNengParentListAdapter;
import com.djsearch.bean.SortBean;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;

/**
 * 万能搜页面
 * @author chenyang2
 *
 */
public class WanNengSearchActivity extends BaseActivity {
	private Context mContext;
	private Button backBtn,gridViewBtn,wanNengSearchBtn;//设置按钮，顶部右边第一个按钮（平铺图按钮），搜索按钮
	private RelativeLayout wanNengLoaLayout,mainCenterLayout;
	private ListView parentSortListView,childSortListView;//父类分类listview，子类分类listview
	private List<String> parentSortList = new ArrayList<String>();
	private WanNengParentListAdapter wanNengParentListAdapter;
	private WanNengChildListAdapter wanNengChildListAdapter;
	private Map<String, List<SortBean>> sortMap;
	private List<SortBean> sortBeanList = new ArrayList<SortBean>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.wanneng_search_layout);
		mContext = this;
		wanNengParentListAdapter = new WanNengParentListAdapter(mContext,parentSortList);
		wanNengChildListAdapter = new WanNengChildListAdapter(mContext,sortBeanList);
		sortMap = new HashMap<String, List<SortBean>>();
		//得到屏幕的分辨率
		getDisPlayMetrics();
		//初始化主界面
		initView();
		//初始化主界面相关点击事件
		initOnClick();
		//初始化handler
		initHandler();
	}
	
	
	
	@Override
	public void initView() {
		backBtn = (Button)findViewById(R.id.backBtn);
		gridViewBtn = (Button)findViewById(R.id.gridViewBtn);
//		wanNengSearchBtn = (Button)findViewById(R.id.wannengSearchBtn);
		wanNengLoaLayout = (RelativeLayout)findViewById(R.id.wannengLocation);
		mainCenterLayout = (RelativeLayout)findViewById(R.id.wanNengCenterLayout);
		setMainCenterLayout(mainCenterLayout);
		parentSortListView = (ListView)findViewById(R.id.parentSortListView);
		parentSortListView.setAdapter(wanNengParentListAdapter);
		childSortListView =(ListView)findViewById(R.id.childSortListView);
		childSortListView.setDividerHeight(0);
		childSortListView.setAdapter(wanNengChildListAdapter);
		requestSortData();
		
	}
	@Override
	public void initOnClick() {
		// TODO Auto-generated method stub
		wanNengLoaLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				popWindow(v);
			}
		});
		
		backBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(mContext, MainActivity.class, 1);
			}
		});
		
//		childSortListView.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view,
//					int position, long id) {
//				// TODO Auto-generated method stub
//				Intent intent=new Intent();
//		        intent.setClass(mContext, WebViewActivity.class);
//		        intent.putExtra("url", sortBeanList.get(position).getUrl());
//		        startActivity(intent);
//		        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
//				
//			}
//		});
		
		parentSortListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0) {
					wanNengChildListAdapter.refresh(sortMap.get("usuallySeacher"));
//					view.setBackgroundResource(R.drawable.wanneng_search_selected);
				} else if (position == 1) {
					wanNengChildListAdapter.refresh(sortMap.get("foodSearch"));
				} else if (position == 2) {
					wanNengChildListAdapter.refresh(sortMap.get("specialySearch"));
				} else if (position == 3) {
					wanNengChildListAdapter.refresh(sortMap.get("lifeSearch"));
				} else if (position == 4) {
					wanNengChildListAdapter.refresh(sortMap.get("peopleSearch"));
				} else if (position == 5) {
					wanNengChildListAdapter.refresh(sortMap.get("houseSearch"));
				} else if (position == 6) {
					wanNengChildListAdapter.refresh(sortMap.get("shopSearch"));
				}
				for(int j=0;j<parent.getCount();j++){
		            View v=parent.getChildAt(j);
//		            if (position == j) {
//		            	v.setBackgroundResource(R.drawable.wanneng_search_selected);
//		            } else {
//		            	v.setBackgroundResource(R.drawable.wanneng_search_nomal);
//		            }
				}
			}
		});
	}
	
	/**
	 * 请求分类数据
	 */
	private void requestSortData() {
		IRequest request = new JSONReq("wanneng_search");
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
				showDialog("正在加载...");
			}
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
						Toast.makeText(mContext, "成功", 5000).show();
						getDataToResolve(response);
				} else if (IResponse.Fail==result) {
					Toast.makeText(mContext, "失败", 5000).show();
				}
					missDialog();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
//				super.onFailure(e, response);
				missDialog();
//				Log.e("GROUP", response);
//				missProgressBar();
			}
			
		});
	
		
	}
	
	
	
	
	
	
	
	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		startActivity(WanNengSearchActivity.this, MainActivity.class, 2);
		return super.onKeyDown(keyCode, event);
	}



	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		
	}


	/**
	 * "houseSearch":[{"subjectType":"13","subjectImage":"http:\/\/localhost:8080\/awp\/img\/test.gif","url":"http:\/\/119.161.221.204:8088\/awp\/awp\/jsp\/business!p.shtml?data={\"queryByType\":\"医院\",\"page\":\"1\",\"pageNum\":\"10\"}","subjectName":"医院"}],
	 * "shopSearch":[{"subjectType":"10","subjectImage":"http:\/\/localhost:8080\/awp\/img\/test.gif","url":"http:\/\/119.161.221.204:8088\/awp\/awp\/jsp\/business!p.shtml?data={\"queryByType\":\"酒吧\",\"page\":\"1\",\"pageNum\":\"10\"}","subjectName":"酒吧"}],
	 * 
	 */

	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub
		try {
			JSONObject obJsonObject = (JSONObject) response.get("returnMessage");
			JSONArray jsonArray = obJsonObject.getJSONArray("usuallySeacher");
			parentSortList.add("常用");
			resolveJsonArray(jsonArray,"usuallySeacher");
			JSONArray jsonArrayTwo = obJsonObject.getJSONArray("foodSearch");
			parentSortList.add("餐饮");
			resolveJsonArray(jsonArrayTwo,"foodSearch");
			
			JSONArray jsonArrayThree = obJsonObject.getJSONArray("specialySearch");
			parentSortList.add("特色");
			resolveJsonArray(jsonArrayThree,"specialySearch");
			
			JSONArray jsonArrayFour = obJsonObject.getJSONArray("lifeSearch");
			parentSortList.add("生活");
			resolveJsonArray(jsonArrayFour,"lifeSearch");
			
			JSONArray jsonArrayFive = obJsonObject.getJSONArray("peopleSearch");
			parentSortList.add("休闲");
			resolveJsonArray(jsonArrayFive,"peopleSearch");
			
			JSONArray jsonArraySix = obJsonObject.getJSONArray("houseSearch");
			parentSortList.add("生活");
			resolveJsonArray(jsonArraySix,"houseSearch");
			
			JSONArray jsonArraySeve = obJsonObject.getJSONArray("shopSearch");
			parentSortList.add("生活");
			resolveJsonArray(jsonArraySeve,"shopSearch");
			
			wanNengParentListAdapter.refresh(parentSortList);
			wanNengChildListAdapter.refresh(sortMap.get("usuallySeacher"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	private void resolveJsonArray(JSONArray jsonArray,String whichType) {
		List<SortBean> listSortBean = new ArrayList<SortBean>();
		for (int i = 0; i < jsonArray.length(); i++) {
			SortBean sortBean = new SortBean();
			try {
				JSONObject obJsonObject = jsonArray.getJSONObject(i);
				sortBean.setSubjectName(obJsonObject.getString("subjectName"));
				sortBean.setSubjectImage(obJsonObject.getString("subjectImage"));
				sortBean.setSubjectType(obJsonObject.getString("subjectType"));
				sortBean.setUrl(obJsonObject.getString("url"));
				listSortBean.add(sortBean);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		sortMap.put(whichType, listSortBean);
	}
	
	
}
